import { LitElement, html, css } from 'lit'
import { customElement, property, query } from 'lit/decorators.js'

type ToDoItem = {
  text: string
  completed: boolean
}

@customElement('my-element')
class MyElement extends LitElement {
  static styles = css`
    .todo{
      display: grid;
      place-items: center;
    }
    .todo .container{
      width: 400px;
    }
    h1{
      text-align: center;
    }
    li {
      cursor: pointer;
    }
    li:hover {
      color: #777;
    }
    .completed {
      text-decoration-line: line-through;
      color: #e53d30;
    }
  `

  @property({ attribute: false })
  listItems: ToDoItem[] = [
    { text: 'JavaScript', completed: true },
    { text: 'Vue', completed: false },
    { text: 'React', completed: false },
    { text: 'Lit', completed: false },
  ]

  @property()
  hideCompleted: boolean = false

  @query('#newItem')
  input!: HTMLInputElement

  private addToDo() {
    if (!this.input.value) return
    this.listItems.push({ text: this.input.value, completed: false })
    this.input.value = ''
    this.requestUpdate()
  }

  private keyTrigger(e: KeyboardEvent) {
    if (e.code === 'Enter') {
      this.addToDo()
    }
  }

  private toggleCompleted(item: ToDoItem) {
    item.completed = !item.completed
    this.requestUpdate()
  }

  private setHideCompleted() {
    this.hideCompleted = !this.hideCompleted
  }

  private deleteHandle(_: ToDoItem, index: number) {
    const sure = window.confirm('Are you sure?')
    if (sure) {
      this.listItems.splice(index, 1)
      this.requestUpdate()
    }
  }

  render() {
    const items = this.hideCompleted ? this.listItems.filter((item) => !item.completed) : this.listItems
    const todos = html`
      <ul>
        ${items.map(
          (item, index) =>
            html` <li>
              <span class=${item.completed ? 'completed' : ''}>${item.text}</span>
              <button @click=${() => this.toggleCompleted(item)}>${item.completed ? '-' : 'O'}</button>
              <button @click=${() => this.deleteHandle(item, index)}>X</button>
            </li>`
        )}
      </ul>
    `
    return html`
      <div class="todo">
        <div class="container">
          <h1>Lit-ToDo</h1>
          ${todos}
          <input id="newItem" aria-label="New item" @keyup=${this.keyTrigger} />
          <button @click=${this.addToDo}>Add</button>
          <br />
          <label>
            <input type="checkbox" @change=${this.setHideCompleted} ?checked=${this.hideCompleted} />
            Hide completed
          </label>
        </div>
      </div>
    `
  }
}
